<template>
  <div class="app-container">
    <!--查询表单-->
    <el-form :inline="true" class="demo-form-inline" size="mini">
      <el-form-item>
        <el-input v-model="teacherQuery.name" placeholder="讲师名"/>
      </el-form-item>

      <el-form-item>
        <el-select v-model="teacherQuery.level" clearable placeholder="讲师头衔">
          <el-option :value="1" label="高级讲师"/>
          <el-option :value="2" label="首席讲师"/>
        </el-select>
      </el-form-item>

      <el-form-item label="添加时间">
        <el-date-picker
          v-model="teacherQuery.begin"
          type="datetime"
          placeholder="选择开始时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          default-time="00:00:00"
        />
      </el-form-item>

      <el-form-item>
        <el-date-picker
          v-model="teacherQuery.end"
          type="datetime"
          placeholder="选择截止时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          default-time="00:00:00"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getList()">查询</el-button>
        <el-button type="default" icon="el-icon-refresh" size="mini" @click="resetData()">清空</el-button>
        <el-button type="primary" icon="el-icon-circle-plus-outline" size="mini" @click="showCreate()"
                   v-permission="'teacher:add'">添加
        </el-button>
        </el-form-item>

    </el-form>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="数据加载中"
      border
      fit
      highlight-current-row>

      <el-table-column
        label="序号"
        width="70"
        align="center">
        <template slot-scope="scope">
          {{ (page - 1) * limit + scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column prop="name" label="名称" width="80"/>

      <el-table-column label="头像" width="70">
        <template slot-scope="scope">
          <img :src="scope.row.avatar" class="user-avatar">
        </template>
      </el-table-column>

      <el-table-column label="头衔" width="80">
        <template slot-scope="scope">
          <!---->
          {{ scope.row.level===1?'高级讲师':'首席讲师' }}
        </template>
      </el-table-column>

      <el-table-column label="资历">
        <template slot-scope="scope">
          <div class="intro" :title="scope.row.intro">
            {{scope.row.intro}}
          </div>
        </template>
      </el-table-column>

      <el-table-column prop="gmtCreate" label="添加时间" sortable width="160"/>

      <el-table-column prop="sort" label="排序" sortable width="80"/>

      <el-table-column label="操作" width="200" align="center">
        <template slot-scope="scope">
          <!--<router-link :to="'edit/'+scope.row.id">-->
          <el-button type="primary" size="mini" icon="el-icon-edit" @click="showUpdate(scope.$index)"
                     v-permission="'teacher:update'">修改
          </el-button>
          <!-- </router-link>-->
          <el-button type="danger" size="mini" icon="el-icon-delete" @click="removeDataById(scope.row.id)"
                     v-permission="'teacher:delete'">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      :current-page="page"
      :page-size="limit"
      :total="total"
      background
      style="padding: 30px 0; text-align: center;"
      layout="total, prev, pager, next, jumper"
      @current-change="getList"
    />
    <!--添加弹出框-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" top="2vh" width="800px">

      <el-form class="small-space" :model="tempData" label-position="left"
               style='width: 500px; margin-left:50px;'>
        <el-form-item label="讲师名称">
          <el-input v-model="tempData.name" style="width: 400px"/>
        </el-form-item>

        <!-- 讲师头像 -->
        <el-form-item label="讲师头像">
          <el-upload
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :action="BASE_URL+'/eduoss/fileoss?host=teacher'"
            class="avatar-uploader">
            <img v-if="tempData.avatar" :src="tempData.avatar" style="width: 150px;height: 150px">
            <el-button type="primary" v-else>上传<i class="el-icon-upload el-icon--right"></i></el-button>
          </el-upload>

        </el-form-item>

        <el-form-item label="讲师排序">
          <el-input-number v-model="tempData.sort" controls-position="right" :min="0" :max="100"/>
        </el-form-item>

        <el-form-item label="讲师头衔">
          <el-select v-model="tempData.level" clearable placeholder="请选择">
            <!--
              数据类型一定要和取出的json中的一致，否则没法回填
              因此，这里value使用动态绑定的值，保证其数据类型是number
            -->
            <el-option :value="1" label="高级讲师"/>
            <el-option :value="2" label="首席讲师"/>
          </el-select>
        </el-form-item>

        <el-form-item label="讲师资历">
          <el-input v-model="tempData.career" style="width: 400px"/>
        </el-form-item>

        <el-form-item label="讲师简介">
          <el-input v-model="tempData.intro" :rows="3" type="textarea" style="width: 400px"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus==='create'" type="success" @click="createData">创 建</el-button>
        <el-button type="primary" v-else @click="updateData">修 改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  const defaultForm = {
    name: '',
    sort: 0,
    level: '',
    career: '',
    intro: '',
    avatar: ""
  }
  export default {
    data() {
      return {
        listLoading: true, // 是否显示loading信息
        list: null, //查询后返回数据
        page: 1, //当前页
        limit: 5, //每页记录数
        total: 0, //总记录数
        teacherQuery: {},//条件封装对象
        dialogStatus: 'create',
        dialogFormVisible: false,
        textMap: {
          update: '编辑',
          create: '创建文章'
        },
        BASE_URL: process.env.BASE_URL,//获取dev.env.js中的BASE_API
        tempData: defaultForm,
        saveBtnDisabled: false // 保存按钮是否禁用,
      }
    },
    created() {
      this.getList()
    },
    methods: {
      //获取教师列表
      getList(page = 1) {
        //查询列表
        if (!this.hasPerm('teacher:list')) {
          return
        }
        this.page = page
        this.api({
          url: `/teacher/pageListTeacherCondition/${this.page}/${this.limit}`,
          method: "post",
          data: this.teacherQuery
        }).then(data => {
          console.log(data)
          this.list = data.list //列表
          this.total = data.totalCount //总数
          this.listLoading = false
        })
      },
      //重置查询条件
      resetData() {
        this.teacherQuery = {}
        this.getList()
      },
      //删除
      removeDataById(id) {
        // debugger
        //MessageBox 在utils/request.js中已引用
        this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return this.api({
            url: `/teacher/${id}`,
            method: "delete",
          })
        }).then(() => {
          this.getList(this.page)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        }).catch((response) => { // 失败
          if (response === 'cancel') {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          } else {
            this.$message({
              type: 'error',
              message: '删除失败'
            })
          }
        })
      },
      showCreate() {
        //显示新增对话框
        this.tempData = defaultForm;
        this.dialogStatus = "create"
        this.dialogFormVisible = true
      },
      showUpdate($index) {
        //显示修改对话框
        this.tempData = Object.assign({}, this.list[$index]);//深拷贝
        this.dialogStatus = "update"
        this.dialogFormVisible = true
      },
      //关闭对话框
      closeDialog() {
        this.resetData()
        this.dialogFormVisible = false
      },
      createData() {
        if (!this.tempData.avatar) this.tempData.avatar = process.env.OSS_PATH + "/avatar/teacher-default.png"
        this.api({
          url: "/teacher/addTeacher",
          method: "post",
          data: this.tempData
        }).then(() => {
          this.closeDialog();
          return this.$message({
            type: 'success',
            message: '保存成功!'
          });
        })
      },
      updateData() {
        this.api({
          url: "/teacher/updateTeacher",
          method: "post",
          data: this.tempData
        }).then(() => {
          this.closeDialog();
          return this.$message({
            type: 'success',
            message: '修改成功!'
          });
        })
      },
      //5. 上传封面成功调用的方法
      handleAvatarSuccess(res, file) {
        this.tempData.avatar = res.info

      },
      //6. 上传之前调用的方法 约定文件类型
      beforeAvatarUpload(file) {
        const isLt2M = file.size / 1024 / 1024 < 2
        const typeArr = ['image/jpeg', 'image/png', 'image/jpg']
        const isImage = typeArr.find(x => x === file.type);
        if (!isImage) {
          this.$message.error('不支持上传此文件类型!')
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!')
        }
        return isImage && isLt2M
      },

    }

  }
</script>

<style scoped>
  .user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 10px;
  }

  .intro {
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
  }
</style>
